<?php
namespace App\Http\Controllers\API\V1;

use Request;
use App\Ext\Common\UploadImage;

class EditorController extends APIController
{
    /**
     *
     * 上传文章图片接口
     * 返回summernote编辑器的值
     *
     * @param $token
     * @param $path
     * @return mixed
     */
    public function uploadImage($token, $path)
    {
        $response = array();
        # 验证访问者身份
        if (!$this->authGuest($token)) {
            $response['state'] = '没有上传文件的权限，请重新登录后尝试!';
            return response()->json($response);
        }
        if (count($_FILES) < 1) {
            $response['state'] = '没有接受到上传的文件!';
            return response()->json($response);
        }
        $files = Request::file('image');
        $images = array();
        foreach ($files as $file) {
            # 原始文件名
            $originalName = $file->getClientOriginalName();
            # 新文件名
            $fileName = time() . substr(mt_rand(), 5);
            $fileName = $fileName . '.' . $file->getClientOriginalExtension();
            # 验证图片大小
            $sizeMax = formatBytes($file->getMaxFilesize());
            $sizeMax = floor($sizeMax);
            $fileSize = formatBytes($file->getClientSize());
            if ($fileSize > $sizeMax) {
                $response['state'] = '文件"' . $originalName . '"容量为' . $fileSize . 'MB，超过上传文件大小限制，文件上传的最大限制为' . $sizeMax . 'MB';
                return response()->json($response);
            }
            # 验证图片格式
            $image = new UploadImage();
            $mime = ['jpg','jpeg','png']; # 文件类型限制
            if (!$image->checkMime($file, $mime)) {
                $response['state'] = '上传的文件格式限制为"jpg,jpeg,png"';
                return response()->json($response);
            }

            # 保存文件对象
            $imageParam = [
                'max' => ['w' => 1024, 'watermark' => $this->filePath['water_mark']],
                'small' => ['w' => 24, 'h' => 24],
            ];
            $result = $image->save($file, $this->path[$path], $fileName, $imageParam);
            # 上传到云存储
            if ($result) $images[] = $result;
        }
        $response['state'] = 'SUCCESS';
        $response['file'] = $images;
        return response()->json($response);
    }
}